from fastapi import Depends
import typing as T
from sqlmodel import select, delete, update, insert
import logging


from ..init.Global import Session
from . import table
from ..dto.Dept import Dept


class _DeptsMapper:
    def __call__(self, session: Session):
        self.session = session
        return self

    async def list(self):
        result = (await self.session.execute(select(table.deptTable))).scalars().all()
        logging.info(f"DeptsMapper.list() result: {result}")
        return result

    async def delete(self, id: int):
        await self.session.execute(
            delete(table.deptTable).where(table.deptTable.id == id)
        )

    async def save(self, dept: Dept):
        await self.session.execute(
            insert(table.deptTable).values(dept.model_dump(exclude_none=True))
        )

    async def getById(self, id: int):
        result = (
            await self.session.execute(
                select(table.deptTable).where(table.deptTable.id == id)
            )
        ).scalar()
        logging.info(f"DeptsMapper.getById() result: {result}")
        return result

    async def update(self, dept: Dept):
        await self.session.execute(
            update(table.deptTable)
            .where(table.deptTable.id == dept.id)
            .values(**dept.model_dump(exclude_unset=True))
        )


DeptsMapper = T.Annotated[_DeptsMapper, Depends(_DeptsMapper())]
